package com.fancy.learncenter.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonClassItemBean;
import com.fancy.learncenter.bean.CartoonClassListBean;
import com.fancy.learncenter.bean.CartoonJoinClassResultBean;
import com.fancy.learncenter.bean.CartoonStudentDataBean;
import com.fancy.learncenter.bean.CartoonTurnipResultBean;
import com.fancy.learncenter.bean.CheckCreatClassDataBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.callback.AddClassPopuImpl;
import com.fancy.learncenter.ui.callback.CartoonAddClassImpl;
import com.fancy.learncenter.ui.view.CartoonAddClassPopu;
import com.fancy.learncenter.ui.view.CartoonListClassPopu;
import com.fancy.learncenter.ui.view.EnterCartoonPopupWindow;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 学生端首页
 */
public class CartoonChildHomeActivity extends BaseActivity implements View.OnClickListener {

    public static boolean isMute = false;

    PermissionHelper mHelper;

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.total_turnip)
    TextView totalTurnip;
    @Bind(R.id.everyday_listen_speek)
    ImageView everydayListenSpeek;
    @Bind(R.id.class_name)
    TextView className;
    @Bind(R.id.change_class_image)
    ImageView changeClassImage;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.error_center_image)
    ImageView errorCenterImage;
    @Bind(R.id.expand_image)
    ImageView expandImage;
    @Bind(R.id.my_work)
    ImageView myWork;
    @Bind(R.id.rootView)
    RelativeLayout rootView;
    @Bind(R.id.bg_music)
    SimpleDraweeView bgMusic;

    private CartoonListClassPopu listClassPopu;
    private List<CartoonClassItemBean> classList;
    CartoonAddClassPopu addClassPopu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_child_first, Status.STATUS);
        ButterKnife.bind(this);
        onClickListener();

        changePermission();


        enterCartoonPopupWindow = new EnterCartoonPopupWindow(this, rootView);
        enterCartoonPopupWindow.setDisCallBack(new EnterCartoonPopupWindow.DisCallBack() {
            @Override
            public void disCallBack() {
                recordPlayer = new MAudioPlayer(CartoonChildHomeActivity.this, R.raw.cartoon_home);
                recordPlayer.setLooping(true);
                recordPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
                    @Override
                    public void playerPause() {
                        bgMusic.setImageURI("res://com.superservice.lya/" + R.mipmap.home_music_pause);
                    }

                    @Override
                    public void playerCompletion(MediaPlayer mp) {
                        bgMusic.setImageURI("res://com.superservice.lya/" + R.mipmap.home_music_pause);
                    }

                    @Override
                    public void playerPrepared(MediaPlayer mp) {
                    }

                    @Override
                    public void playerStart() {

                        String urlPath = "res://" + CartoonChildHomeActivity.this.getPackageName() + "/" + R.mipmap.home_music;
                        DraweeController draweeController =
                                Fresco.newDraweeControllerBuilder()
                                        .setUri(urlPath)
                                        .setOldController(bgMusic.getController())
                                        .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
                                        .build();
                        bgMusic.setController(draweeController);
                    }

                    @Override
                    public void playerError(MediaPlayer mp, int what, int extra) {

                    }
                });
                recordPlayer.play();

//                String urlPath = "res://" + CartoonChildHomeActivity.this.getPackageName() + "/" + R.mipmap.home_music;
//                DraweeController draweeController =
//                        Fresco.newDraweeControllerBuilder()
//                                .setUri(urlPath)
//                                .setOldController(bgMusic.getController())
//                                .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
//                                .build();
//                bgMusic.setController(draweeController);
            }
        });

        className.setText(MyApplication.classNameStr);


    }

    @Override
    public void finish() {


        enterCartoonPopupWindow.setDisCallBack(null);
        enterCartoonPopupWindow.dismiss();


        if (recordPlayer != null) {
            recordPlayer.pause();
            recordPlayer.stop();
            recordPlayer = null;
        }


        finishActivity();

        super.finish();
    }

    private void finishActivity() {
        Intent intent = getIntent();
        setResult(MainActivity.CARTOON_SUDENT, intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!isCloseMus && recordPlayer != null && !recordPlayer.isPlaying()) {
            recordPlayer.play();
        }
        checkClass();

    }

    MAudioPlayer recordPlayer;

    EnterCartoonPopupWindow enterCartoonPopupWindow;
    boolean flag;

    @Override
    protected void onPause() {
        super.onPause();

        if (recordPlayer != null && recordPlayer.isPlaying()) {
            recordPlayer.pause();
        }

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!flag) {
            enterCartoonPopupWindow.showPopupWindow();
            flag = true;
        }

    }


    private void onClickListener() {

        back.setOnClickListener(this);
        everydayListenSpeek.setOnClickListener(this);
        myWork.setOnClickListener(this);
        errorCenterImage.setOnClickListener(this);
        expandImage.setOnClickListener(this);
        totalTurnip.setOnClickListener(this);
        bottomLayout.setOnClickListener(this);
        bgMusic.setOnClickListener(this);
        back.setOnClickListener(this);
    }

    private void showClssListPopu() {
        if (listClassPopu == null) {
            listClassPopu = new CartoonListClassPopu(this, changeClassImage, classList);
        }

        listClassPopu.setDatas(classList);

        if (addClassPopu != null && addClassPopu.isShowing()) {
            addClassPopu.dismiss();
        }

        listClassPopu.setListener(new CartoonAddClassImpl() {
            @Override
            public void addClass() {
                showAddClassPopu();
            }

            @Override
            public void onClick(int position) {

                MyApplication.classIDStr = classList.get(position).getClassId() + "";
                MyApplication.classNameStr = classList.get(position).getClassName();
                SPUtils.putClassID(MyApplication.classIDStr + "," + MyApplication.classNameStr);

                className.setText(MyApplication.classNameStr);
                listClassPopu.dismiss();
            }
        });

        listClassPopu.showPopupWindow();
    }

    private void showAddClassPopu() {

        if (addClassPopu == null) {

            addClassPopu = new CartoonAddClassPopu(this, bottomLayout);

        }

        if (listClassPopu != null && listClassPopu.isShowing()) {
            listClassPopu.dismiss();
        }

        addClassPopu.setListener(new AddClassPopuImpl() {
            @Override
            public void okClick(String editStr) {
                addClass(editStr);
            }

            @Override
            public void cancelClick() {

                showClssListPopu();
            }
        });

        addClassPopu.showPopupWindow();
    }

    private void getTurnipData() {

        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().getRadishRank(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonStudentDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonStudentDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonStudentDataBean>() {
                    @Override
                    public void success(CartoonStudentDataBean dataBean) {

                        if (dataBean != null) {
                            int turnipNum = Double.valueOf(dataBean.getResult().getTotalRadishCount()).intValue();
                            totalTurnip.setText("" + turnipNum);
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();

            }
        });

    }


    private void getClassList() {
        bottomLayout.setEnabled(false);
        classList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().cartoonListOfClass(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                bottomLayout.setEnabled(true);
                BaseBean<CartoonClassListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonClassListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonClassListBean>() {
                    @Override
                    public void success(CartoonClassListBean dataBean) {
                        if (dataBean != null) {
                            classList.removeAll(classList);
                            classList.addAll(dataBean.getResult());
                        }

                    }

                    @Override
                    public void fail(String errorCode) {
                    }
                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                bottomLayout.setEnabled(true);
            }
        });

    }


    private void getClassData() {
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().cartoonListOfClass(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonClassListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonClassListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonClassListBean>() {
                    @Override
                    public void success(CartoonClassListBean dataBean) {
                        if (dataBean != null) {

                            if (dataBean.getResult() != null && dataBean.getResult().size() > 0) {
                                MyApplication.classNameStr = dataBean.getResult().get(0).getClassName();
                                MyApplication.classIDStr = dataBean.getResult().get(0).getClassId() + "";
                                SPUtils.putClassID(MyApplication.classIDStr + "," + MyApplication.classNameStr);
                                className.setText(MyApplication.classNameStr);
                            } else {
                                ToastUtil.show("请先加入班级");
                                finish();
                            }

                        }

                    }

                    @Override
                    public void fail(String errorCode) {
                    }
                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });

    }

    private void addClass(String editStr) {

        Map<String, Object> map = new HashMap<>();
        map.put("classNo", editStr);
        HttpMehtod.getInstance().cartoonJoinClass(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonJoinClassResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonJoinClassResultBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonJoinClassResultBean>() {
                    @Override
                    public void success(CartoonJoinClassResultBean dataBean) {
                        ToastUtil.show("班级加入成功");

                        getClassList();

                        SPUtils.putClassID(dataBean.getResult().getClassId() + "," + dataBean.getResult().getClassName());

                        MyApplication.classIDStr = dataBean.getResult().getClassId() + "";
                        MyApplication.classNameStr = dataBean.getResult().getClassName() + "";
                        className.setText(MyApplication.classNameStr);

                    }

                    @Override
                    public void fail(String errorCode) {
                        ToastUtil.show("班级号输入有误");
                    }
                }).dealData();
            }
        });
    }


    boolean isCloseMus = false;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.bg_music:

                if (recordPlayer.isPlaying()) {
                    recordPlayer.pause();
                    isCloseMus = true;
                } else {
                    recordPlayer.play();
                    isCloseMus = false;
                }
                break;
            case R.id.everyday_listen_speek:

                if (!TextUtils.isEmpty(MyApplication.classIDStr)) {
                    intent = new Intent(getBaseContext(), EverydayListenSpeekActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.show("小朋友请先加入班级吧");
                }

                break;
            case R.id.my_work:

                if (!TextUtils.isEmpty(MyApplication.classIDStr)) {
                    intent = new Intent(getBaseContext(), CartoonMyWorkActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.show("小朋友请先加入班级吧");
                }


                break;
            case R.id.error_center_image:

                if (!TextUtils.isEmpty(MyApplication.classIDStr)) {
                    intent = new Intent(getBaseContext(), CartoonErrorCenterActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.show("小朋友请先加入班级吧");
                }


                break;
            case R.id.expand_image:


                if (!TextUtils.isEmpty(MyApplication.classIDStr)) {
                    intent = new Intent(getBaseContext(), CatoonExpandActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.show("小朋友请先加入班级吧");
                }


                break;
            case R.id.back:
                finish();
                break;
            case R.id.bottom_layout:
                getClassList();

                showClssListPopu();
                break;
            case R.id.total_turnip:
                if (!TextUtils.isEmpty(MyApplication.classIDStr)) {
                    intent = new Intent(getBaseContext(), TurnipBillBoardActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.show("小朋友请先加入班级吧");
                }


                break;
        }
    }

    private void checkClass() {
        Map<String, Object> map = new HashMap<>();

        map.put("classId", MyApplication.classIDStr);
        HttpMehtod.getInstance().checkClass(map, new CustomNetSubscriber(this, false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                BaseBean<CheckCreatClassDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CheckCreatClassDataBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CheckCreatClassDataBean>() {
                    @Override
                    public void success(CheckCreatClassDataBean dataBean) {

                        if (!dataBean.isResult()) {
                            MyApplication.classIDStr = "";
                            MyApplication.classNameStr = "";
                            SPUtils.putClassID("");
                            className.setText("");
                            getClassData();
                        } else {
                            getTurnipData();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }

        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void changePermission() {
        mHelper = new PermissionHelper(this);
        ArrayList<String> permissionList = new ArrayList<>();
        if (!mHelper.hasPermissions(this, Manifest.permission.RECORD_AUDIO)) {
            permissionList.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!mHelper.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        mHelper.requestPermissions("请授予非凡学习文件获取权限！",
                new PermissionHelper.PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
                        LogUtil.MyLog("mHelper", "========确认=======");
                    }

                    @Override
                    public void doAfterDenied(final String... permission) {
                        LogUtil.MyLog("mHelper", "========拒绝=======" + permission.toString());
                        mHelper.showMessageOKCancel(getResources().getString(R.string.recode_permission), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ArrayList<String> permissionList = new ArrayList<>();
                                if (!mHelper.hasPermissions(CartoonChildHomeActivity.this, Manifest.permission.RECORD_AUDIO)) {
                                    permissionList.add(Manifest.permission.RECORD_AUDIO);
                                }
                                if (!mHelper.hasPermissions(CartoonChildHomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                }
                                mHelper.executePermissionsRequest(CartoonChildHomeActivity.this, (String[]) permissionList.toArray(new String[permissionList.size()]), mHelper.REQUEST_PERMISSION_CODE);
                            }
                        });
                    }
                }, (String[]) permissionList.toArray(new String[permissionList.size()]));
    }

    @Override
    public void onBackPressed() {
        if (listClassPopu != null && listClassPopu.isShowing()) {
            listClassPopu.dismiss();
        } else {
            super.onBackPressed();
        }
    }
}
